const fetch = require('node-fetch')

function getParams (url, params) {
  const paramsArr = []
  params = params || {}
  Object.keys(params).map((k) => {
    paramsArr.push(`${k}=${params[k]}`)
  })
  if (paramsArr.length > 0) {
    url += url.indexOf('?') > -1 ? ':' : '?'
    url += (paramsArr.length > 0) ? paramsArr.join('&') : ''
  }
  return url
}
function $http (url, method, body, headers) {
  body = body ? JSON.stringify(body) : '{}'
  headers = { 'Content-Type': 'application/json' }
  yy.log.info(url, body, headers)
  return fetch(url, {method, body, headers}).then(res => res.json())
}
module.exports = {
  getFile (url, params) {
    url = getParams(url, params)
    return fetch(url)
  },
  get (url, params) {
    url = getParams(url, params)
    return $http(url, 'GET')
  },
  post (url, params) {
    return $http(url, 'POST', params)
  },
  put (url, params) {
    return $http(url, 'PUT', params)
  },
  del (url, params) {
    return $http(url, 'DELETE', params)
  }
}
